package com.borrow.jiemihua.mainUI.activity;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;

import com.borrow.jiemihua.R;
import com.borrow.jiemihua.base.BaseActivity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * ----选择头像
 */
public class SelectPhotoActivity extends BaseActivity implements View.OnClickListener {
    private Bitmap head;//头像Bitmap
    private static String path = "/sdcard/myHead/";//sd路径

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_photo);

        initViews();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {

    }

    private void initViews() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, CONTEXT_INCLUDE_CODE);
        }
        findViewById(R.id.btn_takephoto).setOnClickListener(this);
        findViewById(R.id.btn_photos).setOnClickListener(this);
        findViewById(R.id.btn_close).setOnClickListener(this);

        Bitmap bt = BitmapFactory.decodeFile(path + "head.jpg");//从Sd中找头像，转换成Bitmap
        if (bt != null) {
            @SuppressWarnings("deprecation")
            Drawable drawable = new BitmapDrawable(bt);//转换成drawable
        } else {
            /**
             *	如果SD里面没有则需要从服务器取头像，取回来的头像再保存在SD中
             *
             */
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //拍照
            case R.id.btn_takephoto:
                Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                        "head.jpg")));
                startActivityForResult(intent2, 2);//采用ForResult打开
                break;

            //相册选择
            case R.id.btn_photos:
                Intent intent1 = new Intent(Intent.ACTION_PICK, null);
                intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent1, 1);
                break;

            //取消
            case R.id.btn_close:
                finish();
                break;
            default:
                break;
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                   /* cropPhoto(data.getData());//裁剪图片
                    System.out.println(data.getData()+"=======1");*/
                    //数据是使用Intent返回
                    String path = getPath(this, data.getData());
//                    System.out.println(path + "=======1");
                    Intent intent = new Intent();

                    //把返回数据存入Intent
                    intent.putExtra("head", path);

                    intent.putExtra("from", "1");

                    //设置返回数据
                    SelectPhotoActivity.this.setResult(RESULT_OK, intent);

                    //关闭Activity
                    SelectPhotoActivity.this.finish();
                }
                break;
            case 2:
                if (resultCode == RESULT_OK) {
                   /* File temp = new File(Environment.getExternalStorageDirectory()
                            + "/head.jpg");
                    System.out.println(temp+"==========2");*/
//                    cropPhoto(Uri.fromFile(temp));//裁剪图片

                    //数据是使用Intent返回
                    Intent intent = new Intent();

                    //把返回数据存入Intent
//                    intent.putExtra("head", Uri.fromFile(temp));
                    intent.putExtra("from", "2");

                    //设置返回数据
                    SelectPhotoActivity.this.setResult(RESULT_OK, intent);

                    //关闭Activity
                    SelectPhotoActivity.this.finish();
                }
                break;
            case 3:
                if (data != null) {
                    Bundle extras = data.getExtras();
                    head = extras.getParcelable("data");
                    if (head != null) {
                        /**
                         * 上传服务器代码
                         */
                        setPicToView(head);//保存在SD卡中

                    }
                }
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 调用系统的裁剪
     *
     * @param uri
     */
    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }

    private void setPicToView(Bitmap mBitmap) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
            return;
        }
        FileOutputStream b = null;
        File file = new File(path);
        file.mkdirs();// 创建文件夹
        String fileName = path + "head.jpg";//图片名字
        try {
            b = new FileOutputStream(fileName);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
//        } finally {
//            try {
//                //关闭流
////                b.flush();
////                b.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
    }

    public static String getPath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

}
